﻿using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DataBaseBackUpUtil
{
    [DisallowConcurrentExecution]
    public class BackUpJob : IJob, IInterruptableJob
    {

        public void Execute(IJobExecutionContext context)
        {
            try
            {
                JobDataMap data = context.JobDetail.JobDataMap;
                string MySqlInstallPath = data.GetString("MySqlInstallPath");
                string BackUpFolderPath = data.GetString("BackUpFolderPath");
                string UserName = data.GetString("UserName");
                string Password = data.GetString("Password");
                string DataBaseName = data.GetString("DataBaseName");
                string ReceiveMailAddress = data.GetString("ReceiveMailAddress");
                string BackUpFilePath = string.Empty;
                BackUpUtil.BackUpDB(MySqlInstallPath, BackUpFolderPath, UserName, Password, DataBaseName, ref BackUpFilePath, (s, arg) =>
                {
                    if (!string.IsNullOrEmpty(BackUpFilePath) && File.Exists(BackUpFilePath))
                    {
                        DataBaseBackUpUtil.FMail.MailModel mailmodel = new DataBaseBackUpUtil.FMail.MailModel();
                        mailmodel.Content = string.Format("{0}数据库{1}备份", DateTime.Now.ToString("yyyy年MM月dd日"), DataBaseName);
                        mailmodel.ReceiverAddress = ReceiveMailAddress;
                        mailmodel.ReceiverName = "数据库DBA";
                        mailmodel.Title = "数据库备份邮件发送";
                        mailmodel.SenderName = "系统管理员";
                        mailmodel.SenderAddress = "11111@qq.com";
                        mailmodel.SenderPassword = "1111111";
                        mailmodel.AttachFilePath = BackUpFilePath;
                        FMail.SendMail(mailmodel);
                        FLog.WriteLog("发送邮件成功");
                    }
                    else
                    {
                        FLog.WriteLog("备份文件路径不存在");
                    }
                    FLog.WriteLog("执行BackUpJob成功");
                });
                FLog.WriteLog("备份文件路径：" + BackUpFilePath);


            }
            catch (Exception ex)
            {
                FLog.WriteLog("执行BackUpJob失败，异常信息：" + ex.Message);
                throw;
            }
        }

        public void Interrupt()
        {
            FLog.WriteLog("中断BackUpJob");
        }
    }
}
